package org.microframework.cloud.gateway.controller;

import lombok.extern.slf4j.Slf4j;
import org.microframework.cloud.gateway.config.DynamicRouteConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 路由管理控制器
 * 提供路由的增删改查功能
 */
@Slf4j
@RestController
@RequestMapping("/routes")
public class RouteController {
    
    @Autowired
    private DynamicRouteConfig dynamicRouteConfig;
    
    /**
     * 获取所有路由
     */
    @GetMapping
    public Mono<Map<String, Object>> getRoutes() {
        List<RouteDefinition> routes = dynamicRouteConfig.getRouteDefinitions();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", routes);
        result.put("message", "获取路由列表成功");
        result.put("success", true);
        return Mono.just(result);
    }
    
    /**
     * 添加路由
     */
    @PostMapping
    public Mono<Map<String, Object>> addRoute(@RequestBody RouteDefinition definition) {
        log.info("添加路由: {}", definition.getId());
        String result = dynamicRouteConfig.add(definition);
        Map<String, Object> response = new HashMap<>();
        response.put("code", "success".equals(result) ? 200 : 500);
        response.put("message", "success".equals(result) ? "添加路由成功" : result);
        response.put("success", "success".equals(result));
        return Mono.just(response);
    }
    
    /**
     * 更新路由
     */
    @PutMapping
    public Mono<Map<String, Object>> updateRoute(@RequestBody RouteDefinition definition) {
        log.info("更新路由: {}", definition.getId());
        String result = dynamicRouteConfig.update(definition);
        Map<String, Object> response = new HashMap<>();
        response.put("code", "success".equals(result) ? 200 : 500);
        response.put("message", "success".equals(result) ? "更新路由成功" : result);
        response.put("success", "success".equals(result));
        return Mono.just(response);
    }
    
    /**
     * 删除路由
     */
    @DeleteMapping("/{id}")
    public Mono<Map<String, Object>> deleteRoute(@PathVariable String id) {
        log.info("删除路由: {}", id);
        String result = dynamicRouteConfig.delete(id);
        Map<String, Object> response = new HashMap<>();
        response.put("code", "success".equals(result) ? 200 : 500);
        response.put("message", "success".equals(result) ? "删除路由成功" : result);
        response.put("success", "success".equals(result));
        return Mono.just(response);
    }
} 